﻿using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using UILibrary;

namespace Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public List<ReagentItemTypeStyle> ReagentItemTypeStyles { get; set; }= new ()
        {

            new(){ 
                Name= "禁用",
                Color = new SolidColorBrush() { Color =(Color) ColorConverter.ConvertFromString("#e0e0e0") },
                IsDisabled=true },
            new(){
                Name= "无",
                Color = new SolidColorBrush() { Color =(Color) ColorConverter.ConvertFromString("#aaa") },
                IsDisabled=true },
            new(){
                Name= "酸",
                Color = new SolidColorBrush() { Color =(Color) ColorConverter.ConvertFromString("#6639b7") },
                IsDisabled=true },
            new(){
                Name= "碱",
                Color = new SolidColorBrush() { Color =(Color) ColorConverter.ConvertFromString("#a626aa") },
                IsDisabled=true },
            new(){
                Name= "水",
                Color = new SolidColorBrush() { Color =(Color) ColorConverter.ConvertFromString("#00aee6") },
                IsDisabled=true },
            new(){
                Name= "试剂",
                Color = new SolidColorBrush() { Color =(Color) ColorConverter.ConvertFromString("#8cb811") },
                IsDisabled=true }
        };
        public MainWindow()
        {
            OrginDatas = create原生数据();

            InitializeComponent();
            DataContext = this;

            //this.createReagentDatas(rb1);
            //this.createReagentDatas(rb2);
            ParseData(OrginDatas);
        }
        public double 用量比阈值Low = .3;
        public double 用量满值 = 100;
        public int 单次用量 = 5;
        public int 药剂盘Count = 64;


        public List<OrginItemData> OrginDatas { get; set; }
        //public void createReagentDatas(ReagentBoard rb)
        //{
        //    var datas = new ObservableCollection<ReagentItemData>();
  
        //       var random  = new Random();
        //    for (int i = 0; i < 药剂盘Count; i++)
        //    {
        //        var project = "项目"+ random.Next(1, 10).ToString();
        //        var 类型 = (ReagentItemType)(
        //                Enum.GetValues(typeof(ReagentItemType)).GetValue(random.Next(Enum.GetValues(typeof(ReagentItemType)).Length)))!;
        //        var percent = 1.0;
        //        var 状态 = ReagentItemState.Normal;

        //        var key = "";
        //        switch (类型)
        //        {
        //            case ReagentItemType.Disabled:
        //            case ReagentItemType.无:
        //                状态 = ReagentItemState.Normal;
        //                break;  
        //            default:
        //                percent = random.Next(0, 100) / (double)100;
        //                if (percent == 0)
        //                {
        //                    状态 = ReagentItemState.Null;
        //                }else if(percent < 用量比阈值Low)
        //                {
        //                    状态 = ReagentItemState.Low;
        //                }
        //                key = $"{project}:{i}";
        //                break;

        //        }
        //        datas.Add(new ReagentItemData()
        //        {
        //            DataKey = key,
        //            Percent = percent,
        //            State = 状态,
        //            Type = 类型,
        //            Index = i,
        //            AvailableCount = ((int)(percent *100))
        //        }); ;
        //    }
        //    rb.DataSource = datas;

        //}
        private void Button_Click1(object sender, RoutedEventArgs e)
        {

            var r = new Random();
            foreach (var item in OrginDatas.Where(d => d.Board == 1))
            {
                item.Depth = r.Next(0, 100);
                var itemData = rb1.DataSource.First(d=>d.Index == item.Pos);
                Computed用量(item, itemData);
            }

        }
        private void Button_Click2(object sender, RoutedEventArgs e)
        {
            var r = new Random();
            foreach (var item in OrginDatas.Where(d => d.Board == 2))
            {
                item.Depth = r.Next(0, 100);
                var itemData = rb2.DataSource.First(d => d.Index == item.Pos);
                Computed用量(item, itemData);
            }
        }


        private List<OrginItemData> create原生数据()
        {
            var types = new List<string> { "R1", "R2", "R2-1", "S1", "S2", "T1", "T2", "T4", "T5","水", "酸", "碱" };

            string[] projects = new string[] { "P1", "P2", "US1", "USX", "WTX", "TX1", "TX2", "SS2", "UVZ","X","XX","XXX","XXXX", "PA", "Pb", "Ux1", "Uc", "WD", "T2", "T3", "ST", "UZ", "X1", "XX2", "XX2X", "XXX3X" };
            string[] containerTypes = new string[] { "C1", "C2", "C3", "C4", "C5", "C6" };

            List<OrginItemData> data = new();
            var random = new Random();
            for (var r= 1;r < 3; r++)
            {

                for (int i = 0; i < 药剂盘Count; i++)
                {
                    //空出禁用或空的槽
                    if(random.Next(1,8)==1)
                    {

                        data.Add(new OrginItemData { Board=r,Pos=i});
                    }
                    else
                    {
                        data.Add(new OrginItemData()
                        {
                            Board = r,
                            ContainerType = containerTypes[random.Next(0, containerTypes.Length)],
                            Type = types[random.Next(0, types.Count)],
                            Project = projects[random.Next(0, projects.Length)],
                            Depth = random.Next(0, 100),
                            Pos = i,
                            No = random.Next(1000, 9999)
                        });
                    }

                }
            }
            return data;
        }
        public List<ReagentGridDataItem> GridDatas { get; set; }
        public List<ReagentItemData<OrginItemData>> ReagentItemDatas { get; set; }
        private void ParseData(List<OrginItemData> data)
        {

            var list = new List<ReagentItemData<OrginItemData>>();
            var gridTableDatas = new ReagentGridDataItem();
            
            var random = new Random();
            foreach (var item in data)
            {
                if(item.Project == null)
                {
                    list.Add( new ReagentItemData<OrginItemData> {
                        Index = item.Pos,
                        State = ReagentItemState.Normal,
                        Type = random.Next(1, 3) == 1 ? "禁用" : "无",
                        Percent = 1,
                        Content = "",
                        DataKey = "",
                        OrginData = item,

                    }); ;
                }
                else
                {

                    var itemData = new ReagentItemData<OrginItemData>()
                    {
                        DataKey = $"{item.Board}:{item.Pos}:{item.Type}:{item.Project}",
                        Content = item.Type,
                        Index = item.Pos,
                        Type = "试剂",
                        OrginData =item,
                    };
                    Computed用量(item, itemData);

                    if (item.Type == "酸" || item.Type == "碱" || item.Type == "水")
                    {
                        itemData.Type = item.Type;

                    }
                    list.Add( itemData);
                }

                
            }

            ReagentItemDatas = list;

            var listx = list.Where(d =>!string.IsNullOrEmpty(d.OrginData.Project)).GroupBy(x => x.OrginData.Project);


            GridDatas = listx.Select(x => {
                return new ReagentGridDataItem()
                {
                    Project = x.Key.ToString()!,
                    RbDatas = new ObservableCollection<ReagentItemData<OrginItemData>>(x.ToList())

                };
            }).ToList();
            GridDataTable.ItemsSource = new ObservableCollection<ReagentGridDataItem>(GridDatas);

            rb1.TypeStyles = ReagentItemTypeStyles;
            rb2.TypeStyles = ReagentItemTypeStyles;

            rb1.DataSource = new ObservableCollection<ReagentItemData>(list.Where(d => d.OrginData.Board == 1));

            rb2.DataSource = new ObservableCollection<ReagentItemData>(list.Where(d => d.OrginData.Board == 2));
        }
        private void Computed用量(OrginItemData orginData,ReagentItemData data)
        {
            var 满量使用次数 = 用量满值 / 单次用量;
            var 剩余次数 = ((int)Math.Floor(orginData.Depth / 单次用量));
            var percent = 剩余次数 / 满量使用次数;

            data.Percent = 剩余次数 / 满量使用次数;
            data.Count = 剩余次数;
            data.State = percent == 0 ? ReagentItemState.Null : percent < 用量比阈值Low ? ReagentItemState.Low : ReagentItemState.Normal;
       
    
        }
        private void RSelectedChanged(object sender, RoutedEventArgs e)
        {
            var data = e.OriginalSource as ReagentItemData<OrginItemData>;
            var project = data!.OrginData.Project;
            if (!string.IsNullOrEmpty(project))
            {

                GridDataTable.SelectedIndex = GridDatas.FindIndex(d => d.Project == project);
                GridDataTable.ScrollIntoView(GridDataTable.SelectedItem);

                //var selectedData = GridDatas[GridDataTable.SelectedIndex];

                //R1DataTable.ItemsSource = OrginDatas.Where(d => d.Board == 1 && selectedData.Project == d.Project);
                //R2DataTable.ItemsSource = OrginDatas.Where(d => d.Board == 2 && selectedData.Project == d.Project);


            }

        }

        //由于需要非逻辑暃的多选中触发(盘中item被点击时触发grid选中，而grid点击选中触发盘中多选)，放弃数据驱动
        private void GridDataTable_SelectChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedData = GridDatas[GridDataTable.SelectedIndex];
            var project = selectedData.Project;


            var r1Datas = selectedData.RbDatas.Where(d => d.OrginData.Board == 1);
            R1DataTable.ItemsSource = r1Datas;
            if (rb1.SelectedIndex > -1)
            {
                R1DataTable.SelectedIndex = r1Datas.ToList().FindIndex(d => d.OrginData.Pos == rb1.SelectedIndex);
            }

            var r2Datas = selectedData.RbDatas.Where(d => d.OrginData.Board == 2);
            R2DataTable.ItemsSource = r2Datas;
            if (rb2.SelectedIndex > -1)
            {
                R2DataTable.SelectedIndex = r2Datas.ToList().FindIndex(d => d.OrginData.Pos == rb2.SelectedIndex);
            }

            rb1.MutilSign(rb1.DataSource.Where(d => ((ReagentItemData<OrginItemData>)d).OrginData.Project == project));
            rb2.MutilSign(rb2.DataSource.Where(d => ((ReagentItemData<OrginItemData>)d).OrginData.Project == project));




        }

        private void RTabTable_MouseDownSelect(object sender, SelectionChangedEventArgs e)
        {
            var el = sender as ListView;
            var r = el.Tag as string;
            var rTable = r == "1" ? R1DataTable : R2DataTable;
            var rb = r == "1" ? rb1 : rb2;

            var orginDataItem = rTable.SelectedValue as ReagentItemData<OrginItemData>;
            if (orginDataItem != null)
            {
                rb.Select(orginDataItem.Index);
            }



        }
    }
    /// <summary>
    /// 试剂数据
    /// </summary>
    public class OrginItemData : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        /// <summary>
        /// 盘位
        /// </summary>
        private int board { get; set; }
        public int Board
        {
            get { return board; }
            set
            {
                board = value;
                NotifyPropertyChanged();
            }
        }
        /// <summary>
        /// 位置
        /// </summary>
        private int pos {  get; set; }
        public int Pos
        {
            get { return pos; }
            set
            {
                pos = value;
                NotifyPropertyChanged();
            }
        }
        /// <summary>
        /// 试剂类型
        /// </summary>
        private string type { get; set; }
        public string Type
        {
            get { return type; }
            set
            {
                type = value;
                NotifyPropertyChanged();
            }
        }
        /// <summary>
        /// 项目名称
        /// </summary>
        private string project { get; set; }
        public string Project
        {
            get { return project; }
            set
            {
                project = value;
                NotifyPropertyChanged();
            }
        }
        /// <summary>
        /// 容器类型
        /// </summary>
        private string containerType { get; set; }
        public string ContainerType
        {
            get { return containerType; }
            set
            {
                containerType = value;
                NotifyPropertyChanged();
            }
        }
        /// <summary>
        /// 余量高度 ml
        /// </summary>
        private double depth {  get; set; }
        public double Depth
        {
            get { return depth; }
            set
            {
                depth = value;
                NotifyPropertyChanged();
            }
        }
        /// <summary>
        /// 批号
        /// </summary>
        private int no {  get; set; }
        public int No
        {
            get { return no; }
            set
            {
                no = value;
                NotifyPropertyChanged();
            }
        }
    }
    /// <summary>
    /// 右侧汇总数据表项
    /// </summary>
    public class ReagentGridDataItem: INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private string project { get; set; }
        /// <summary>
        /// 序列
        /// </summary>
        public string Project
        {
            get { return project; }
            set
            {
                project = value;
                NotifyPropertyChanged();
            }
        }
        private ObservableCollection<ReagentItemData<OrginItemData>> rbDatas { get; set; }
        /// <summary>
        /// 序列
        /// </summary>
        public ObservableCollection<ReagentItemData<OrginItemData>> RbDatas
        {
            get { return rbDatas; }
            set
            {
                rbDatas = value;
                NotifyPropertyChanged();

                R1Count = RbDatas.Where(d => d.OrginData.Board == 1).Sum(d => d.Count);
                R2Count = RbDatas.Where(d => d.OrginData.Board == 2).Sum(d => d.Count);

                foreach (var rbData in value)
                {
                    if (rbData is INotifyPropertyChanged newNotifyPropertyChanged)
                    {
                        newNotifyPropertyChanged.PropertyChanged += (o, e) =>
                        {
                            R1Count = RbDatas.Where(d => d.OrginData.Board == 1).Sum(d => d.Count);
                            R2Count = RbDatas.Where(d => d.OrginData.Board == 2).Sum(d => d.Count);
                        };
                    }
                    else
                    {
                        throw new NotSupportedException("must be implement INotifyPropertyChanged");
                    }
                }

            }
        }
        private int r1Count;

        public int R1Count
        {
            get { return r1Count; }
            set { r1Count = value;
                NotifyPropertyChanged();
            }
        }
        private int r2Count;
        public int R2Count
        {
            get { return r2Count; }
            set
            {
                r2Count = value;
                NotifyPropertyChanged();
            }
        }
    }
    public class ColorString2BrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var colorString = value as string;
            if (!string.IsNullOrEmpty(colorString))
            {
                return new SolidColorBrush((Color)ColorConverter.ConvertFromString(colorString));
            }
            throw new NotImplementedException();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}